/*
 * @Description: token生成
 * @Autor: HuiSir<www.zuifengyun.com>
 * @Date: 2022-06-01 17:32:37
 * @LastEditTime: 2022-06-06 10:46:39
 */
import Encrypt from "../helper/Encrypt.js"

/**
 * Token生成和解码
 * @param skey 加密秘钥
 */
export default (skey: string) => {
    const encrypt = new Encrypt(skey)

    /**
     * 生成token
     * @param userid 用户id
     */
    const createToken = (userid: string): string => {
        const curTime = Date.now() //当前时间戳(保证每次生成不同的token)
        const curTime36 = curTime.toString(36) //转为36进制
        return encrypt.encode(`${userid},${curTime36}`)
    }

    /**
     * token解码
     * @param token token
     */
    const decodeToken = (token: string): { id?: string, loginTime?: Number } => {
        try {
            const [id, curTime36] = encrypt.decode(token).split(',')

            const loginTime = parseInt(curTime36, 36) //36进制转10进制

            if ((loginTime + '').length !== 13) {
                return {}
            }

            return { id, loginTime }
        } catch (err) {
            return {}
        }
    }

    return {
        createToken,
        decodeToken
    }
}